#include "uv.h"
#include <stdlib.h>
#include <string.h>

typedef struct
{
    uv_write_t req;
    uv_buf_t buf;
} write_req_t;

uv_loop_t *loop;
uv_timer_t vzReq;

void free_write_req(uv_write_t *req)
{
    write_req_t *wr = (write_req_t *)req;
    free(wr->buf.base);
    free(wr);
}

void write_cb(uv_write_t *req, int status)
{
    printf("%d write success", status);
    if (status)
    {
        fprintf(stderr, "Write error %s\n", uv_strerror(status));
    }
    free_write_req(req);
}

void on_connect(uv_connect_t *req, int status)
{
    printf("connect!!!!!!!!");

    uv_buf_t buf;

    buf.base = "Hello TTY\n";
    buf.len = strlen(buf.base);
    write_req_t *wr_rq = (write_req_t *)malloc(sizeof(write_req_t));
    uv_write((uv_write_t *)wr_rq, req->handle, &buf, 1, write_cb);
}

int main(int argc, char const *argv[])
{
    loop = uv_default_loop();

    uv_tcp_t *socket = (uv_tcp_t *)malloc(sizeof(uv_tcp_t));
    uv_tcp_init(loop, socket);

    uv_connect_t *connect = (uv_connect_t *)malloc(sizeof(uv_connect_t));

    struct sockaddr_in dest;
    uv_ip4_addr("100.98.138.128", 5000, &dest);

    uv_tcp_connect(connect, socket, (const struct sockaddr *)&dest, on_connect);
    uv_tcp_connect(connect, socket, (const struct sockaddr *)&dest, on_connect);
    uv_tcp_connect(connect, socket, (const struct sockaddr *)&dest, on_connect);

    return uv_run(loop, UV_RUN_DEFAULT);
}
